package top.fangw.tenant.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import top.fangw.common.core.entity.BaseIdNameVo;
import top.fangw.tenant.mapper.SourceDatabaseInfoMapper;
import top.fangw.tenant.pojo.dto.DatasourceInfoPageQueryDto;
import top.fangw.tenant.pojo.entity.DatasourceInfo;
import top.fangw.tenant.mapper.DatasourceInfoMapper;
import top.fangw.tenant.pojo.entity.SourceDatabaseInfo;
import top.fangw.tenant.service.IDatasourceInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.fangw.common.core.exception.BizException;
import top.fangw.common.mybatis.annotation.DyDataSource;
import top.fangw.common.mybatis.util.TestConnectionUtil;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用途：用于保存系统中除基础信息外的所有数据源信息 服务实现类
 * </p>
 *
 * @author fangw
 * @since 2024-01-16
 */
@Service
@RequiredArgsConstructor

public class DatasourceInfoServiceImpl extends ServiceImpl<DatasourceInfoMapper, DatasourceInfo> implements IDatasourceInfoService {

    private final SourceDatabaseInfoMapper sourceDatabaseInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @DyDataSource
    public int add(DatasourceInfo datasourceInfo) {
        List<DatasourceInfo> datasourceInfos = this.baseMapper.selectList(new LambdaQueryWrapper<>(DatasourceInfo.class).eq(DatasourceInfo::getDatasourceName, datasourceInfo.getDatasourceName()));
        if (datasourceInfos.size() > 0) {
            throw new BizException("数据源名称已存在");
        }
        return this.baseMapper.insert(datasourceInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @DyDataSource
    @Override
    public void delete(String id) {
        // 1、查询数据源信息
        DatasourceInfo datasourceInfo = this.baseMapper.selectById(id);
        // 2、删除数据源数据库信息
        sourceDatabaseInfoMapper.delete(new LambdaQueryWrapper<>(SourceDatabaseInfo.class).eq(SourceDatabaseInfo::getDatasourceName, datasourceInfo.getDatasourceName()));
        // 3、删除数据源信息
        this.baseMapper.deleteById(id);
    }

    @Override
    public IPage<DatasourceInfo> pageQuery(DatasourceInfoPageQueryDto pageQueryDto) {
        IPage<DatasourceInfo> page = new Page<>(pageQueryDto.getCurrent(), pageQueryDto.getSize());
        LambdaQueryWrapper<DatasourceInfo> queryWrapper = new LambdaQueryWrapper<>(DatasourceInfo.class);
        if (StrUtil.isNotBlank(pageQueryDto.getDataSourceName())) {
            queryWrapper
                    .like(DatasourceInfo::getDatasourceName, pageQueryDto.getDataSourceName());
        }
        if (StrUtil.isNotBlank(pageQueryDto.getName())) {
            queryWrapper
                    .like(DatasourceInfo::getName, pageQueryDto.getName());
        }
        IPage<DatasourceInfo> datasourceInfoPage = this.baseMapper.selectPage(page, queryWrapper);
        if(datasourceInfoPage.getRecords().size() > 0) {
            List<DatasourceInfo> collect = datasourceInfoPage.getRecords().stream().map(item -> item.setPassword(null)).toList();
            datasourceInfoPage.setRecords(collect);
        }
        return datasourceInfoPage;
    }

    @Override
    public void testConnection(DatasourceInfo datasourceInfo) {

        Boolean aBoolean = TestConnectionUtil.testConnection(datasourceInfo.getUrl(), datasourceInfo.getUsername(), datasourceInfo.getPassword(), datasourceInfo.getDriverClassName());
        if (!aBoolean) {
            throw new BizException("连接失败");
        }
    }

    @Override
    public List<BaseIdNameVo> listDataSource() {
        return this.baseMapper.listDataSource();
    }


}
